package com.jiyinit.web.core.mobile.controller;

import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.util.JsonEntityTransform;
import com.jiyinit.core.framework.base.util.LogUtil;
import com.jiyinit.web.core.business.dto.MessageRequest;
import com.jiyinit.web.core.business.dto.UserRequest;
import com.jiyinit.web.core.business.entity.TabCoreFunEntity;
import com.jiyinit.web.core.business.service.FunctionServiceImpl;
import com.jiyinit.web.core.business.service.OrgServiceImpl;
import com.jiyinit.web.core.common.logic.ParamCheckLogic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 用户管理
 *
 * @author zhaolaiwei
 * @version 1.0
 * @date 2017/4/13 9:01
 * @since 1.0
 */
@Controller
@RequestMapping("/mobile/function")
public class MfuntionController {

    /**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(MfuntionController.class);

    @Resource(name = "core.paramCheckLogic")
    private ParamCheckLogic paramCheckLogic;

    @Resource(name = "function.serviceImpl")
    private FunctionServiceImpl functionServiceImpl;

    @Resource(name = "core.orgServiceImpl")
    private OrgServiceImpl orgService;

    /**
     * 按条件查询用户信息
     *
     * @param request
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/findFunction")
    public ResponseEntity<ResponseDto> findFuns(HttpServletRequest request) {
        UserRequest userRequest = this.getJsonToTaskRequest(request);
        if(userRequest.getUserId()==null){
            return new ResponseEntity<>(ResponseDto.responseFail("用户Id不能为空"), HttpStatus.OK);
        }
        if(userRequest.getOrgId() == null){
            return new ResponseEntity<>(ResponseDto.responseFail("机构Id不能为空"), HttpStatus.OK);
        }
        //用户的顶级机构
        Integer orgId = orgService.getTopParentOrgId(userRequest.getOrgId());
        List<TabCoreFunEntity> funList = functionServiceImpl.getFunByUserId(orgId,userRequest.getUserId());
        return   new ResponseEntity<>(ResponseDto.responseOK(funList), HttpStatus.OK);
    }

    private UserRequest getJsonToTaskRequest(HttpServletRequest request){
        String logJson = request.getParameter("request_json");
        LogUtil.info(LOGGER, "logJson:{}", logJson);
        UserRequest userRequest = (UserRequest) JsonEntityTransform.json2Object(logJson, UserRequest.class);
        return userRequest;
    }
}
